package com.zjut.an.user.action;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.sun.mail.handlers.message_rfc822;
import com.zjut.an.config.manager.AnConfigManager;
import com.zjut.an.log.dao.AnLog;
import com.zjut.an.log.manager.AnLogManager;
import com.zjut.an.user.dao.AnUser;
import com.zjut.an.user.manager.AnUserManager;
import com.zjut.an.util.email.SendsimpleMail;
import com.zjut.an.util.module.PageModule;
import com.zjut.an.util.system.Config;
import com.zjut.an.util.system.Status;
import com.zjut.an.util.tools.DateUtil;
import com.zjut.an.util.tools.JSONUtilClass;
import com.zjut.an.util.tools.JSONUtilClassTime;
import com.zjut.an.util.tools.MD5;

public class AnUserAction extends ActionSupport implements
ServletResponseAware, ServletRequestAware, ModelDriven<AnUser>{

	private HttpServletRequest request;
	private HttpServletResponse response;
	private HttpSession session;
	
	private AnUser obj;
	private Map<String , Object> dataMap;
	private int page = 0, limit = 10;
	private String order;
	private String sort;
	private String search;
	private String rowstr;
	
	@Resource(name = "AnUserManager")
	private AnUserManager manager;
	
	@Resource(name = "AnLogManager")
	private AnLogManager logManager;
	
	@Resource(name = "AnConfigManager")
	private AnConfigManager anConfigManager;
	
	@Resource(name = "MD5")
	private MD5 md5;
	
	@Resource(name = "DateUtil")
	private DateUtil dateutil;
	
	public String anUserList() throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		dataMap = new HashMap<String, Object>();
		if(search!=null) {
			obj = new AnUser();
			obj.setEmail(search);
		}
		PageModule module = manager.getDataByInstance(page, limit, sort, order, obj);
		dataMap.put("rows", module.getObjects());
		dataMap.put("total", module.getTotal()); 
		obj = null; 
		return SUCCESS;
	}
	
	@SuppressWarnings("unchecked")
	public String anUserDeletes() {
		String objumniJSON = rowstr;
		manager.deleteDatas(JSONUtilClassTime.getDTOList(objumniJSON, AnUser.class));
		dataMap = new HashMap<String, Object>();
		dataMap.put("flag", "success");
		return SUCCESS;
	}
	
	public String anUserAdd() throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		dataMap = new HashMap<String, Object>();
		String objumniJSON = rowstr;
		obj = (AnUser)JSONUtilClass.getDTO(objumniJSON, AnUser.class);
		obj.setPassword(md5.toMD5(obj.getPassword()));
		obj.setLastlogin(Timestamp.valueOf(dateutil.getCurrentDate5()));
		AnUser obaccount = new AnUser();
		obaccount.setAccount(obj.getAccount());
		if(manager.getDataByInstance(1, 1, null, null, obaccount).getObjects().size()>0) {
			dataMap.put("message", "accountfailed");
		} else {
			dataMap.put("message", "success");
			manager.addData(obj);
		}
		
		obj = null;
		return SUCCESS;
	}
	
	
	public AnConfigManager getAnConfigManager() {
		return anConfigManager;
	}

	public void setAnConfigManager(AnConfigManager anConfigManager) {
		this.anConfigManager = anConfigManager;
	}

	
	public String anUserDelete() {
		String objumniJSON = rowstr;
		manager.deleteData((AnUser)JSONUtilClassTime.getDTO(objumniJSON, AnUser.class));
		dataMap = new HashMap<String, Object>();
		dataMap.put("flag", "success");
		return SUCCESS;
	}
	
	public String anUserUpdate() throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		dataMap = new HashMap<String, Object>();
		String objumniJSON = rowstr;
		AnUser user = (AnUser)JSONUtilClassTime.getDTO(objumniJSON, AnUser.class);
		System.out.print("@@@@"+rowstr);
		obj = manager.getData(user.getUsId());
		if (!user.getPassword().equals(obj.getPassword())) {
			user.setPassword(md5.toMD5(user.getPassword()));
		} 
		
		manager.updateData(user);
		//session.setAttribute("user", user);
		dataMap.put("flag", "success");
		obj = null;
		return SUCCESS;
	}
	
	public String anResetPassword() {
		String objumniJSON = rowstr;
		AnUser user = (AnUser)JSONUtilClassTime.getDTO(objumniJSON, AnUser.class);
		obj = manager.getData(user.getUsId());
		obj.setPassword(md5.toMD5(user.getPassword()));
		obj.setLastlogin(Timestamp.valueOf(dateutil.getCurrentDate5()));
		manager.updateData(obj);
		session.setAttribute("user", obj);
		return SUCCESS;
	}
	
	public String anUserSave() {
		obj = (AnUser)(JSONUtilClass.getDTOArray(rowstr, AnUser.class)[0]);
		if (obj.getUsId()!=null) {
			//-------update-------
			manager.updateData(obj);
		} else {
			//-------insert-------
			manager.addData(obj);
		}
		rowstr = null;
		return SUCCESS;
	}
	
	
	public String anUserLogin() {
		System.out.println("-------UserLogin-------");
		try {
			dataMap = new HashMap<String, Object>();
			String adminJSON = rowstr;
			System.out.println("rand---"+JSONUtilClass.getMapFromJson(adminJSON).get("rand"));
			System.out.println(adminJSON);
			obj = (AnUser)JSONUtilClass.getDTO(adminJSON, AnUser.class);			
			if (!this.checkCode(JSONUtilClass.getMapFromJson(adminJSON).get("rand"), session.getAttribute("rand"))) {
				dataMap.put("flag", "success");
				dataMap.put("message", "randfailed");
			} else if (null==obj.getPassword() || obj.getPassword().trim().length()==0) {
				dataMap.put("message", "failed");
			} else if (null==obj.getPassword() || obj.getPassword().trim().length()==0) {
				dataMap.put("message", "failed");
			} else {			
				obj.setPassword(md5.toMD5(URLDecoder.decode(obj.getPassword(),"utf-8")));
				PageModule pm = manager.getDataByInstance(1, 1, null,null,obj);
				if (pm.getTotal()>0) {
					obj = (AnUser)pm.getObjects().get(0);
					if(obj.getActive().equals(Status.ON.getStatus())) {
						obj.setLastlogin(Timestamp.valueOf(dateutil.getCurrentDate5()));
						manager.updateData(obj);
						
						session.setAttribute("user", obj);
						//session.setAttribute("admin", obj);
						
						AnLog log = new AnLog("专家日志",obj.getAccount()+"于"+dateutil.getCurrentDate5()+" 登陆成功", dateutil.getCurrentDate5());
						logManager.addData(log);
						dataMap.put("message", "success");
					} else {
						dataMap.put("message", "failed");
					}				
				} else {
					dataMap.put("message", "failed");
				}
			}		
		} catch (Exception e) {
			e.printStackTrace();
			dataMap.put("message", "failed");
		}		
		return SUCCESS;
	}
	
	public String getAccount() {
		dataMap = new HashMap<String, Object>();
		obj = new AnUser();
		obj.setAccount(request.getParameter("account"));
		if (manager.getDataByInstance(1, 1, null, null, obj).getObjects().size()==0) {
			dataMap.put("getdata", "true");
		} else {
			dataMap.put("getdata", "false");
		}
		return SUCCESS;		
	}
	
	public String getEmail() {
		dataMap = new HashMap<String, Object>();
		obj = new AnUser(); 
		obj.setEmail(request.getParameter("email"));
		if (manager.getDataByInstance(1, 1, null, null, obj).getObjects().size()==0) {
			dataMap.put("getdata", "true");
		} else {
			dataMap.put("getdata", "false");
		}
		return SUCCESS;		
	}

	private boolean checkCode(Object input, Object sessioncode) {
		if (null!=input && null!=sessioncode && input.toString().equals(sessioncode.toString())) {
			return true;
		} else {
			return false;
		}
	}
	
	@Override
	public AnUser getModel() {
		if (null == obj) {
			obj = new AnUser();
		}
		return obj;
	}

	@Override
	public void setServletRequest(HttpServletRequest arg0) {
		request = arg0;
		session = request.getSession();
	}

	@Override
	public void setServletResponse(HttpServletResponse arg0) {
		response = arg0;
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

	public HttpSession getSession() {
		return session;
	}

	public void setSession(HttpSession session) {
		this.session = session;
	}

	public AnUser getAl() {
		return obj;
	}

	public void setAl(AnUser obj) {
		this.obj = obj;
	}

	public Map<String, Object> getDataMap() {
		return dataMap;
	}

	public void setDataMap(Map<String, Object> dataMap) {
		this.dataMap = dataMap;
	}

	public String getRowstr() {
		return rowstr;
	}

	public void setRowstr(String rowstr) {
		this.rowstr = rowstr;
	}

	public AnUserManager getManager() {
		return manager;
	}

	public void setManager(AnUserManager manager) {
		this.manager = manager;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public String getOrder() {
		return order;
	}

	public void setOrder(String order) {
		this.order = order;
	}

	public String getSort() {
		return sort;
	}

	public void setSort(String sort) {
		this.sort = sort;
	}

	public String getSearch() {
		return search;
	}

	public void setSearch(String search) {
		this.search = search;
	}

}
